package com.unipay.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.unipay.cmn.client.DictFeignClient;
import com.unipay.hosp.repository.HospitalRepository;
import com.unipay.hosp.service.HospitalService;
import com.unipay.model.hosp.Hospital;
import com.unipay.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project: yitong_parent
 * @Author: C.yu
 * @Time: 2023-04-02 21:29:05
 * @Desc: TODO
 */
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void save(Map<String, Object> paramMap) {
        //把参数map集合转换 MongoDB的document 对象Hospital
        String mapString = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);

        //判断是否存在该上传hosp
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);  //mongodb数据库，查询

        //如果存在，进行修改
        if (hospitalExist != null) {
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            //TODO---报错（75）---
            hospitalRepository.deleteById(hospitalExist.getId());
            hospitalRepository.save(hospital);
        } else {//如果不存在，进行添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    //Hosp列表，条件分页查询
    @Override
    public Page<Hospital> selPageHospptal(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //（1）创建pageable对象，0为第一页
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        //（2）创建条件匹配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //（3）实例化对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        Example<Hospital> example = Example.of(hospital, exampleMatcher);
        //（4）调用方法实现查询
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);
        System.out.println("hospitalPage: " + hospitalPage);
        //TODO 获取查询list集合，遍历进行Hosp等级封装
        //Stream<Hospital> stream = hospitalPage.getContent().stream();
        hospitalPage.getContent().stream().forEach(item ->
                this.setHospitalHosType(item));
        return hospitalPage;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1){
            //Optional<Hospital> byId = hospitalRepository.findById(id);
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Map<String, Object> showHospDetail(String id) {
        Map<String, Object> result = new HashMap<>();
        //（1）医院基本信息（包含医院等级）
        //Hospital hospital = hospitalRepository.findById(id).get();
        Hospital hospital = this.setHospitalHosType(hospitalRepository.findById(id).get());
        result.put("hospital", hospital);
        //（2）预约规则，单独处理
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复显示
        //hospital.setBookingRule(null);
        return result;
    }

    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospital != null){
            return hospital.getHosname();
        }
        return null;
    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        List<Hospital> hospitalByHosnameLike = hospitalRepository.findHospitalByHosnameLike(hosname);
        return hospitalByHosnameLike;
    }

    @Override
    public Map<String, Object> getHospDetail(String hoscode) {
        Map<String, Object> result = new HashMap<String, Object>();
        //Map<String, Object> hospDetail = this.getHospDetail(hoscode);
        Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hoscode);
        Hospital hospital = this.setHospitalHosType(hospitalByHoscode);
        result.put("hospital", hospital);
        result.put("bookingRule", hospital.getBookingRule());
        //清空，重复
        hospital.setBookingRule(null);
        return result;
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospitalByHoscode;
    }

    //TODO ---Hospotal接口，远程调用数据字典---
    //获取查询list集合，遍历进行医院等级封装
    private Hospital setHospitalHosType(Hospital hospital) {
        //（1）根据dictCode（Hostype、Province...）和value获取医院等级名称
        String hostypeName = dictFeignClient.getName("Hostype", hospital.getHostype());
        String province = dictFeignClient.getName(hospital.getProvinceCode());
        String city = dictFeignClient.getName(hospital.getCityCode());
        String district = dictFeignClient.getName(hospital.getDistrictCode());
        /*
         * （2）参数封装
         *   @ApiModelProperty(value = "其他参数")
         *   @Transient //被该注解标注的，将不会被录入到数据库中。只作为普通的javaBean属性
         *   private Map<String,Object> param = new HashMap<>();
         **/
        hospital.getParam().put("detailAddr", province + city + district);
        hospital.getParam().put("hostypeName", hostypeName);
        return hospital;
    }

}
